#
# catalog_tasks.py
#
# Generates JSON and HTML caches for public and dashboard controllers and
# views.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Copyright 2010- Jeremy Nelson
#
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from django.utils import simplejson

import FRBRData,MODSData,logging
from catalog_manager import getRecord


class WorkersRequestHandler(webapp.RequestHandler):

    def get(self):
        self.response.out.write('''<form action="/tasks" method="POST">
                                   <input name="letter" type="text">
                                   <input type='submit'>''')




    def post(self):
        if self.request.get('letter'):
            taskqueue.add(url='/tasks/worker/alpha', params={'letter':
                                                       self.request.get('letter')})
        if self.request.get('key'):
            taskqueue.add(url='/tasks/worker/concept',
                          params={'key':
                                  self.request.get('key')})
        self.response.out.write("IN POST")
##        self.redirect("/")


class AlphaTitleJSONWorker(webapp.RequestHandler):
    ''' Generates JSON representation that is stored in memecache.'''

    def get(self):
        self.response.out.write("IN ALPHATITLEJSONWORKER")

    def post(self):
        first_letter = self.request.get('letter')
        json_output = {'endeavors':[],
                       'display_form':first_letter.upper()}
        all_titles = MODSData.titleInfo.all()
        titles = []
        for title in all_titles:
            if title.title[0] == first_letter.lower():
                titles.append(title)
        for title in titles:
            purchased_dbs = FRBRData.PurchasedElectronicResourceEndeavor.all().filter('title',
                                                                                      title)
            websites = FRBRData.WebSiteEndeavor.all().filter('title',title)                    
            for resource in purchased_dbs:
                json_output['endeavors'].append(getRecord(resource))
            for resource in websites:
                json_output['endeavors'].append(getRecord(resource))
        json_output['endeavors'] = sorted(json_output['endeavors'],
                                          key=lambda x: x['display_form'].lower())

        memcache.add('FRBRData.Endeavors.title.%s' % json_output['display_form'],
                      simplejson.dumps(json_output))


class ConceptJSONWorker(webapp.RequestHandler):
    ''' Generates JSON representation that is stored in memecache.'''

    def post(self):
        concept_key = self.request.get('key')
        def transaction_method():
            concept = FRBRData.Concept.get_by_key_name(concept_key)
            if concept is None:
                raise RuntimeError("Concept with key=%s not found" %\
                                   concept_key)
            json_output = {'display_form':concept.display_form,
                           'endeavors':[],
                           'key':str(concept_key)}
            works = FRBRData.IndividualWork.all().filter("subjects=",concept.key())
            for work in works:
                purchased_dbs = FRBRData.PurchasedElectronicResourceEndeavor.all().filter('work',
                                                                                          work)
                websites = FRBRData.WebSiteEndeavor.all().filter('work',work)                    
                for resource in purchased_dbs:
                    json_output['endeavors'].append(getRecord(resource))
                for resource in websites:
                    json_output['endeavors'].append(getRecord(resource))
            json_output['endeavors'] = sorted(json_output['endeavors'],
                                              key=lambda x: x['display_form'].lower())
            memecache.add('FRBRData.Concept.%s' % json_ouput['key'],
                          simplejson.dumps(json_output))
        db.run_in_transaction(transaction_method)
        
def main():
    run_wsgi_app(webapp.WSGIApplication([
        ('/tasks',WorkersRequestHandler),
        ('/tasks/worker/concept', ConceptJSONWorker),
        ('/tasks/worker/alpha',AlphaTitleJSONWorker),
    ]))

if __name__ == '__main__':
    main()
